﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Nirvana
{
    [CustomPropertyDrawer(typeof(LayerMaskAttribute))]
    public sealed class LayerMaskPropertyDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            int index = property.intValue;
            IEnumerable<int> layerindex = Enumerable.Range(0, 31);
            IEnumerable<string> layername = Enumerable.Select<int, string>(layerindex, (p)=>  LayerMask.LayerToName(p));
            string[] array = Enumerable.ToArray<string>(Enumerable.Where<string>(layername, (p) => !string.IsNullOrEmpty(p)));
            int layer = 0;
            for(int i = 0; i < array.Length; i++)
            {
                int curlayer = 1 << LayerMask.NameToLayer(array[i]);
                if ((index & curlayer) != 0) layer |= 1 << i;
            }
            int num = EditorGUI.MaskField(position, label, layer, array);
            if(num != layer)
            {
                int curIndex = 0;
                if(num != -1)
                {
                    for(int i = 0; i < array.Length; i++)
                    {
                        if((num & 1 << i) != 0)
                        {
                            curIndex |= 1 << LayerMask.NameToLayer(array[i]);
                        }
                    }
                }
                else
                {
                    curIndex = -1;
                }
                index = curIndex;
            }
            if (index != property.intValue) property.intValue = index;

        }

    }
}

